﻿using drawing_print.configure;
using drawing_print.form;
using drawing_print.util;
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace drawing_print.comm
{
    class ServerHelper
    {
        HttpListener httpListener = new HttpListener();
        
        public void Setup(int port = 55555)
        {
            httpListener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
            //如果发送到8080 端口没有被处理，则这里全部受理，+是全部接收
            httpListener.Prefixes.Add(string.Format("http://*:{0}/", port));
            httpListener.Start();//开启服务
            
            Receive();//异步接收请求
        }

        private void Receive()
        {
            httpListener.BeginGetContext(new AsyncCallback(EndReceive), null);
        }

        private void EndReceive(IAsyncResult ar)
        {
            var context = httpListener.EndGetContext(ar);
            Dispather(context);//解析请求
            Receive();
        }
        private void Dispather(HttpListenerContext context)
        {
            HttpListenerRequest request = context.Request;
            HttpListenerResponse response = context.Response;

            string url = request.QueryString["url"];
            string id = request.QueryString["id"];
            string fileType = request.QueryString["fileType"];

            string data = "";
            
            foreach (string key in request.QueryString.AllKeys)
            {
                data += "\"" +key + "\":";
                string val = request.QueryString[key];
                data += "\"" + val + "\",";
            }
            data = data.Remove(data.Length - 1 ,1);
            


            response.StatusCode = 200;
            response.ContentType = "application/json;charset=UTF-8";
            response.ContentEncoding = Encoding.UTF8;
            response.AppendHeader("Content-Type", "application/json;charset=UTF-8");
            StreamWriter writer = new StreamWriter(response.OutputStream, Encoding.UTF8);

                        
            if (string.IsNullOrEmpty(url) || string.IsNullOrEmpty(fileType))
            {
                writer.Write("resultMethod({\"success\": false,\"code\": -1,\"message\": \"\",\"data\": \"参数不全。\"});");
                writer.Close();
                response.Close();
            }
            else if (!FileConver.isSupport(fileType.ToLower()))
            {
                writer.Write("resultMethod({\"success\": false,\"code\": -1,\"message\": \"\",\"data\": \"" + fileType + "文件格式暂时不支持打印。\"});");
                writer.Close();
                response.Close();
            }else if (AppConfig.isWork)
            {
                writer.Write("resultMethod({\"success\": false,\"code\": -1,\"message\": \"\",\"data\": \"插件被占用，请勿频繁操作！\"});");
                writer.Close();
                response.Close();
            }
            else
            {
                // 返回的处理
                string sign = MD5.GetMd532("{\"id\":" + id + "}" + MD5.Token);
                string finalUrl = string.Format("{0}?id={1}&sign={2}&fileType={3}", url, id, sign, fileType);
                //string finalUrl = url;
                AppConfig.log.log("获取文件url：" + finalUrl );
                
                writer.Write("resultMethod({\"success\": true,\"code\": 0,\"message\": \"\",\"data\": { "+data +"}});");
                writer.Close();
                response.Close();

                // 业务处理：下载文件以及文件转换
                //Task.Factory.StartNew(() => {
                    Handle(finalUrl, fileType);
                //});

            }
        }

        public static void Handle(String finalUrl,String fileType)
        {
            AppConfig.isWork = true;
            AppConfig.initialization();
            // 开始解析文件
            Application.Run(new schedule(finalUrl, fileType.ToLower()));
            
        }



    }
}
